package adapter;

import java.util.ArrayList;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.ActionBar.Tab;
import com.actionbarsherlock.app.ActionBar.TabListener;
import com.actionbarsherlock.app.SherlockFragmentActivity;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;

public class FragmentAdapterAccept extends  FragmentPagerAdapter implements TabListener,OnPageChangeListener{

	private final Context context;
	private final ActionBar actionBar;
	private final ViewPager viewPager;
	private final ArrayList<TabInfo> mTabs = new ArrayList<TabInfo>();

	static final class TabInfo {
		private final Class<?> clss;
		private final Bundle args;

		TabInfo(Class<?> _class, Bundle _args) {
			clss = _class;
			args = _args;
		}
	}
	
	public FragmentAdapterAccept(SherlockFragmentActivity activity, ViewPager mViewPager) {
		super(activity.getSupportFragmentManager());
		context = activity;
		actionBar = activity.getSupportActionBar();
		viewPager = mViewPager;
		viewPager.setAdapter(this);
		viewPager.setOnPageChangeListener(this);
	}

	//add tab to view
	public void addTab(ActionBar.Tab tab, Class<?> clss, Bundle args)
	{
		TabInfo info = new TabInfo(clss, args);
		tab.setTag(info);
		tab.setTabListener(this);
		mTabs.add(info);
		actionBar.addTab(tab);
		notifyDataSetChanged();
	}
	@Override
	public Fragment getItem(int arg0) {
		TabInfo info = mTabs.get(arg0);
		return  Fragment.instantiate(context, info.clss.getName(), info.args);
	}

	@Override
	public int getCount() {
		return mTabs.size();
	}

	@Override
	public void onPageScrollStateChanged(int arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onPageScrolled(int arg0, float arg1, int arg2) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onPageSelected(int arg0) {
		actionBar.setSelectedNavigationItem(arg0);
	}

	//tab is selected
	@Override
	public void onTabSelected(Tab tab, FragmentTransaction ft) {
		Object tag = tab.getTag();
		for(int i=0;i<mTabs.size();i++){
			if(mTabs.get(i)==tag){
				viewPager.setCurrentItem(i);
			}
		}
		
	}

	@Override
	public void onTabUnselected(Tab tab, FragmentTransaction ft) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onTabReselected(Tab tab, FragmentTransaction ft) {
		// TODO Auto-generated method stub
		
	}

}
